﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Box2D.XNA;
using Microsoft.Xna.Framework;
using Spinning.Spinning.Unitity;

namespace Spinning.Spinning.Entity.Items
{
    class DynamicBarrier : StaticBarrier
    {
        SingleGamePlayer _player;
        public DynamicBarrier(SingleGamePlayer player)
        {
            Physic_Type = PhysicType.Barrier;
            ZIndex = Constants.item;
            this._player = player;
            isCircle = false;
        }

        public override void OnCreatBody(World world, Unitity.PhysicConnectManager connectManager)
        {
            BodyDef bd = new BodyDef();
            bd.type = BodyType.Dynamic;
            body = world.CreateBody(bd);
            FixtureDef fd = new FixtureDef();

            if (isCircle)
            {
                CircleShape cs = new CircleShape();//圓
                cs._radius = _frameSize.X / 2.45f / Constants.MeterToPixal;
                fd.shape = cs;
            }
            else
            {
                PolygonShape ps = new PolygonShape();//方
                ps.SetAsBox(_frameSize.X / 2.45f / Constants.MeterToPixal, _frameSize.Y / 2.45f / Constants.MeterToPixal);
                fd.shape = ps;
            }

            _fixture = body.CreateFixture(fd);
            body.SetTransform(Vector2.Zero, 0);
            PhysicConnector connector = new PhysicConnector(this, body);
            connectManager.AddPhysicConnector(connector);

            Filter filter = new Filter();
            filter.categoryBits = (ushort)Constants.CategoryBitsItem;
            filter.maskBits = (ushort)Constants.MaskBitsItem;
            Filter = filter;
            _fixture.SetRestitution(1f);
            _fixture.SetDensity(Constants.enemyDensity);
        }

        bool isActive = false;
        public Vector2 itemVelocity;
        public float distance;

        protected override void UpdateSelf(GameTime gameTime)
        {
            base.UpdateSelf(gameTime);

            if (CalculateDistance(_player.Position) && !isActive)
            {
                isActive = true;
                Vector2 playerPos = _player.Position;
                itemVelocity = new Vector2(((playerPos.X - (Position.X + _frameSize.X / 2)) / distance) * 8, -((playerPos.Y - (Position.Y + _frameSize.Y / 2)) / distance) * 8);
                body.SetLinearVelocity(itemVelocity);
            }


            //if (isActive/* && !istouched*/)
            //{
            //    //如何移動 寫在這
            //    body.SetLinearVelocity(itemVelocity);
            //}

        }

        public bool CalculateDistance(Vector2 v)
        {
            distance = (float)Math.Sqrt((v.X - Position.X) * (v.X - Position.X) + (v.Y - Position.Y) * (v.Y - Position.Y));
            return 500 > distance;
        }

    }
}
